package com.lsk.weixin;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.msg.in.event.InQrCodeEvent;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import com.lsk.util.Syslog;

import java.util.Map;

/**
 * Created by Administrator on 2018/10/3.
 */
public class WeiXinService {
    Cache cache= Redis.use(PropKit.get("cache.name"));
    public String processInQrCodeEventService(InQrCodeEvent inQrCodeEvent){

        String key=inQrCodeEvent.getEventKey();
        Map<String,String > map=cache.get(key);
        if (map==null){
            key=key.substring(8);
            map=cache.get(key);
        }
        String type=map.get("type");
        OutTextMsg outTextMsg=new OutTextMsg();
        String openId=inQrCodeEvent.getFromUserName();
        outTextMsg.setToUserName(openId);
        outTextMsg.setFromUserName(inQrCodeEvent.getToUserName());
        outTextMsg.setCreateTime((int) System.currentTimeMillis());
        if ("bindingWeiXin".equals(type)){//后台用户绑定微信扫描事件
            String userId=map.get("userId");
            String querySql="SELECT *from sys_user where id='"+userId+"'";
            Record record=Db.findFirst(querySql);
            String sql="UPDATE  sys_user SET openId='"+openId+"' where id='"+userId+"' ";
            int up=Db.update(sql);
            if (up>0){//绑定成功
                outTextMsg.setContent("尊敬的"+record.getStr("userName")+"您好，您的账户"+
                record.getStr("userCode")+"已成功绑定至当前微信");
            }else {
                outTextMsg.setContent("操作失败，请联系管理员：0371-55080169");
            }
        }else {
            Syslog.error("扫描事件参数不对，请联系管理员：0371-55080169");
        }
        return outTextMsg.toXml();
    }
}
